<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-dialog
      :header="header"
      :visible.sync="visible"
      :onClose="onClose"
      width="80%"
      top="5%"
      :closeOnOverlayClick="false"
    >
      <div v-if="rowIndex==null">
        <t-alert v-if="currentTab==='1'" style="margin-bottom: 20px" theme="info"
                 :message="`当前页面可重复添加。目前已添加数量: ${data7.length} `"/>
        <t-alert v-else style="margin-bottom: 20px" theme="info" :message="`当前页面可重复添加。目前已添加数量: ${data8.length}`"/>
      </div>

      <t-form :disabled="disabled" :colon="true" ref="form" resetType="initial" :data="formData" labelWidth="160px" :rules="rules">
        <t-row style="row-gap:24px">
          <t-col :span="6">
            <t-form-item label="姓名" name="name">
              <t-select
                v-model="formData.name"
                creatable
                filterable
                @change="onLeaderNameChange"
                placeholder="请输入姓名"
                :loading="nameLoading"
                @search="remoteNameMethod"
                :options="nameOptions"
                @create="createNameOptions"
                style="width: 390px"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="身份证号" name="idCard">
              <t-input style="width: 390px" @change="onIdCardChange" placeholder="请输入身份证号" clearable v-model="formData.idCard"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="出生年月" name="birthDate">
              <t-date-picker
                disabled
                :disable-date="{
        after: dayjs().endOf('month').add(-18, 'year').format()}"
                clearable allow-input
                style="width: 390px"
                mode="month"
                v-model="formData.birthDate"></t-date-picker>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="性别" name="sex">
              <t-select clearable style="width:390px" :options="dict.type.sys_user_sex"
                        v-model="formData.sex"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职务" name="duty">
              <t-input clearable style="width:390px" v-model="formData.duty"
              ></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="学历" name="education">
              <t-select style="width: 390px" v-model="formData.education" clearable
                        placeholder="请选择学历"
                        :options="dict.type.education">
              </t-select>
            </t-form-item>
          </t-col>
          <t-col  :span="6">
            <t-form-item  label="学位" name="degree">
              <t-select style="width: 390px" v-model="formData.degree" clearable
                        placeholder="请选择学位"
                        :options="dict.type.degree">
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="技术职称" name="profTitId">
              <t-tree-select style="width:390px" @change="onProfTitIdChange" clearable filterable :treeProps="{keys: {value: 'id',label:'name'}, valueMode: 'onlyLeaf'}"
                             v-model="formData.profTitId" :data="profTitOptions" placeholder="技术职称"></t-tree-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职称" name="profTit">
              <t-select disabled style="width:390px" v-model="formData.profTit" clearable placeholder="请选择职称"
                        :options="dict.type.prof_tit"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="所学专业" name="majorName">
              <t-input style="width: 390px"   clearable v-model="formData.majorName"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="现从事专业" name="majorNowName">
              <t-input style="width: 390px"   clearable v-model="formData.majorNowName"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="所在单位" help="搜索不到请切换外部单位后手输" name="company">
              <t-tree-select  v-if="formData.isInnerCompany==='1'" style="width:390px" clearable filterable
                             :treeProps="{keys: {value: 'label'}}" v-model="formData.company" :data="deptMenuOptions"
                             placeholder="选择单位">
                <template #label>
                                <t-switch
                                  size="medium"
                                  v-model="formData.isInnerCompany"
                                  :label="['内部', '外部']"
                                  :customValue="['1', '0']"
                                  @change="()=>{formData.company=''}"
                                ></t-switch>
                </template>
              </t-tree-select>
              <t-select
                v-else
                v-model="formData.company"
                creatable
                filterable
                placeholder="请输入"
                :loading="companyLoading"
                @search="remoteCompanyMethod"
                :options="companyOptions"
                @create="createCompanyOptions"
                style="width: 390px"
              >
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="formData.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{formData.company=''}"
                  ></t-switch>
                </template>
              </t-select>
<!--              <t-input v-else clearable style="width:390px" v-model="formData.company"></t-input>-->
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="在本项目中承担的任务" name="task">
              <t-input style="width:390px" clearable v-model="formData.task" placeholder="请输入"></t-input>
            </t-form-item>
          </t-col>
          <t-col v-if="currentTab!=='1'" :span="6">
            <t-form-item label="辅助人员" name="isAssist">
              <t-switch
                size="large"
                v-model="formData.isAssist"
                :label="['是', '否']"
                :customValue="['1', '0']"
              ></t-switch>
            </t-form-item>
          </t-col>
          <t-col v-if="phaseType === '4'" :span="6">
            <t-form-item label="对成果创造性贡献" name="contribution" >
              <t-input :disabled="false" style="width:390px" clearable v-model="formData.contribution" placeholder="请输入"></t-input>
            </t-form-item>
          </t-col>

        </t-row>
      </t-form>
      <template #footer v-if="currentTab==='1'">
        <t-button theme="default" @click="onClose">取消</t-button>
        <t-button theme="primary" @click="onSubmit(1)" >保存</t-button>
        <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>
      </template>
      <template #footer v-else>
        <t-button theme="default" @click="onClose">取消</t-button>
        <t-button theme="primary" @click="onSubmit(1)">保存</t-button>
        <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>
      </template>
    </t-dialog>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" >
          <template #title>
            项目负责人(最多三人) <span v-if="showTip" style="color:red;">第一负责人通过【基本信息-项目主要负责人】调整</span>
          </template>
          <t-table  size="small" :selected-row-keys="selectedMemberRowKeys"
                   @select-change="(val)=>{selectedMemberRowKeys=val}" rowKey="id" :data="data7"
                   :columns="columns8">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #name="{ row }">
              <t-link @click="dialog.objId=row.idCard;dialog.header=row.name;dialog.open_detail=true" hover="color" theme="primary">{{ row.name }}</t-link>
            </template>
            <template #sex="{ row }">
              {{ row.sex | filterByDict(dict.type.sys_user_sex) }}
            </template>
<!--            <template #profTit="{ row }">-->
<!--              {{ row.profTit | filterByDict(dict.type.prof_tit) }}-->
<!--            </template>-->
            <template #profTitId="{ row }">
              {{ row.profTitId | filterByTree(profTitOptions, children="children", id="id", label="name") }}({{ row.profTit | filterByDict(dict.type.prof_tit) }})
            </template>
            <template #majorName="{ row }">
              {{ row.majorName }}
            </template>
            <template #majorNowName="{ row }">
              {{ row.majorNowName }}
            </template>
            <template #education="{ row }">
              {{ row.education | filterByDict(dict.type.education) }}
            </template>
            <template #degree="{ row }">
              {{ row.degree | filterByDict(dict.type.degree) }}
            </template>
            <template #isAssist="{ row }">
              {{ row.isAssist === '1' ? '是' : '否' }}
            </template>
            <template #contribution="{ row }">
              <t-textarea
                @change="()=>{ if(row.contribution!==''){row.contributionStatus='default'} }" :status="row.contributionStatus"
                clearable :autosize="{minRows: 3}"
                v-model="row.contribution"
                placeholder="请输入内容"
              >
                <div slot="tips" v-if="row.contributionStatus==='error'">不能为空</div>
              </t-textarea>
            </template>
          </t-table>
          <div v-if="!closeOp" style="margin-top: 10px" class="btn-group-inline">
            <t-button v-if="fromType !== 'acceptance'" :disabled="this.data7.length>=3" @click="currentTab='1';header='添加项目其他负责人';oldMember = null;rowIndex=null;dialogOpen=true;visible=true">新增
            </t-button>
            <t-button @click="upMember">上移</t-button>
            <t-button @click="downMember">下移</t-button>
            <t-button @click="updateMember">修改</t-button>
            <t-button  v-if="fromType !== 'acceptance'"  @click="delMember">删除</t-button>
          </div>
        </t-card>
      </t-col>
    </t-row>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" title="主要研究人员">
          <t-table   size="small" :selected-row-keys="selectedMember1RowKeys"
                   @select-change="(val)=>{selectedMember1RowKeys=val}" rowKey="id" :data="data8" :columns="columns6">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #name="{ row }">
              <t-link @click="dialog.objId=row.idCard;dialog.header=row.name;dialog.open_detail=true" hover="color" theme="primary">{{ row.name }}</t-link>
            </template>
            <template #sex="{ row }">
              {{ row.sex | filterByDict(dict.type.sys_user_sex) }}
            </template>
<!--            <template #profTit="{ row }">-->
<!--              {{ row.profTit | filterByDict(dict.type.prof_tit) }}-->
<!--            </template>-->
            <template #profTitId="{ row }">
              {{ row.profTitId | filterByTree(profTitOptions, children="children", id="id", label="name") }}({{ row.profTit | filterByDict(dict.type.prof_tit) }})
            </template>
            <template #majorName="{ row }">
              {{ row.majorName }}
            </template>
            <template #majorNowName="{ row }">
              {{ row.majorNowName }}
            </template>
            <template #education="{ row }">
              {{ row.education | filterByDict(dict.type.education) }}
            </template>
            <template #degree="{ row }">
              {{ row.degree | filterByDict(dict.type.degree) }}
            </template>
            <template #isAssist="{ row }">
              {{ row.isAssist === '1' ? '是' : '否' }}
            </template>
            <template #contribution="{ row }">
              <t-textarea
                @change="()=>{ if(row.contribution!==''){row.contributionStatus='default'} }" :status="row.contributionStatus"
                clearable :autosize="{minRows: 3}"
                v-model="row.contribution"
                placeholder="请输入内容"
              >
                <div slot="tips" v-if="row.contributionStatus==='error'">不能为空</div>
              </t-textarea>
            </template>
          </t-table>
          <div v-if="!closeOp" style="margin-top: 10px" class="btn-group-inline">
            <t-button v-if="fromType !== 'acceptance'" @click="currentTab='2';header='添加项目主要研究人员';oldMember = null;rowIndex=null;dialogOpen=true;visible=true">新增
            </t-button>
            <t-button @click="upMember2">上移</t-button>
            <t-button @click="downMember2">下移</t-button>
            <t-button @click="updateMember2">修改</t-button>
            <t-button v-if="fromType !== 'acceptance'"  @click="delMember2">删除</t-button>
          </div>
        </t-card>
      </t-col>
    </t-row>
  </div>
  <div v-else style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" title="项目负责人">
          <t-table   size="small" :selected-row-keys="selectedMemberRowKeys"
                   @select-change="(val)=>{selectedMemberRowKeys=val}" rowKey="id" :data="data7"
                   :columns="columns9">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #name="{ row,rowIndex }">
              <t-link @click="dialog.objId=row.idCard;dialog.header=row.name;dialog.open_detail=true" hover="color" theme="primary">
                <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].name!==row.name?'red':''}">{{row.name}}</span>
              </t-link>
            </template>
            <template #sex="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].sex!==row.sex?'red':''}">{{ row.sex | filterByDict(dict.type.sys_user_sex) }}</span>
            </template>
            <template #idCard="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].idCard!==row.idCard?'red':''}">{{ row.idCard }}</span>
            </template>
            <template #birthDate="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].birthDate!==row.birthDate?'red':''}">{{ row.birthDate }}</span>
            </template>
            <template #duty="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].duty!==row.duty?'red':''}">{{ row.duty }}</span>
            </template>
            <!--            <template #profTit="{ row }">-->
            <!--              {{ row.profTit | filterByDict(dict.type.prof_tit) }}-->
            <!--            </template>-->
            <template #profTitId="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].profTitId!==row.profTitId?'red':''}">{{ row.profTitId | filterByTree(profTitOptions, children="children", id="id", label="name") }}({{ row.profTit | filterByDict(dict.type.prof_tit) }})</span>
            </template>
            <template #majorName="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].majorName!==row.majorName?'red':''}">{{ row.majorName }}</span>
            </template>
            <template #majorNowName="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].majorNowName!==row.majorNowName?'red':''}">{{ row.majorNowName }}</span>
            </template>
            <template #education="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].education!==row.education?'red':''}">{{ row.education | filterByDict(dict.type.education) }}</span>
            </template>
            <template #degree="{ row }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].degree!==row.degree?'red':''}">{{ row.degree | filterByDict(dict.type.degree) }}</span>
            </template>
            <template #company="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].company!==row.company?'red':''}">{{ row.company }}</span>
            </template>
            <template #task="{ row, rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].task!==row.task?'red':''}">{{ row.task }}</span>
            </template>
            <template #isAssist="{ row,rowIndex }">
              <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].isAssist!==row.isAssist?'red':''}"> {{ row.isAssist === '1' ? '是' : '否' }}</span>
            </template>
          </t-table>
        </t-card>
      </t-col>
    </t-row>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" title="主要研究人员">
          <t-table   size="small" :selected-row-keys="selectedMember1RowKeys"
                   @select-change="(val)=>{selectedMember1RowKeys=val}" rowKey="id" :data="data8" :columns="columns7">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #name="{ row,rowIndex }">
              <t-link @click="dialog.objId=row.idCard;dialog.header=row.name;dialog.open_detail=true" hover="color" theme="primary">
                <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].name!==row.name?'red':''}">{{row.name}}</span>
              </t-link>
            </template>
            <template #sex="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].sex!==row.sex?'red':''}">{{ row.sex | filterByDict(dict.type.sys_user_sex) }}</span>
            </template>
            <template #idCard="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].idCard!==row.idCard?'red':''}">{{ row.idCard }}</span>
            </template>
            <template #birthDate="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].birthDate!==row.birthDate?'red':''}">{{ row.birthDate }}</span>
            </template>
            <template #duty="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].duty!==row.duty?'red':''}">{{ row.duty }}</span>
            </template>
            <!--            <template #profTit="{ row }">-->
            <!--              {{ row.profTit | filterByDict(dict.type.prof_tit) }}-->
            <!--            </template>-->
            <template #profTitId="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].profTitId!==row.profTitId?'red':''}">{{ row.profTitId | filterByTree(profTitOptions, children="children", id="id", label="name") }}({{ row.profTit | filterByDict(dict.type.prof_tit) }})</span>
            </template>
            <template #majorName="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].majorName!==row.majorName?'red':''}">{{ row.majorName }}</span>
            </template>
            <template #majorNowName="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].majorNowName!==row.majorNowName?'red':''}">{{ row.majorNowName }}</span>
            </template>
            <template #education="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].education!==row.education?'red':''}">{{ row.education | filterByDict(dict.type.education) }}</span>
            </template>
            <template #degree="{ row }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].degree!==row.degree?'red':''}">{{ row.degree | filterByDict(dict.type.degree) }}</span>
            </template>
            <template #company="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].company!==row.company?'red':''}">{{ row.company }}</span>
            </template>
            <template #task="{ row, rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].task!==row.task?'red':''}">{{ row.task }}</span>
            </template>
            <template #isAssist="{ row,rowIndex }">
              <span :style="{color:diffData2.length>=rowIndex+1 && diffData2[rowIndex].isAssist!==row.isAssist?'red':''}"> {{ row.isAssist === '1' ? '是' : '否' }}</span>
            </template>
          </t-table>
        </t-card>
      </t-col>
    </t-row>
    <member-all-detail :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_detail" v-if="dialog.open_detail"></member-all-detail>
  </div>
</template>

<script lang="jsx">
import dayjs from "dayjs"
import {getIdCardBirthday, getIdCardAge} from '@/utils/common';
import memberAllDetail from "@/pages/common/system/components/member-all-detail.vue";


export default {
  name: "project-member",
  dicts:["project_type", "subject_classification", "sys_user_sex", "prof_tit", "degree", "duty", "platform_type", "education", "degree"],
  components:{
    memberAllDetail
  },
  props: {
    value: Array,
    projectId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    showTip: {
      type: Boolean,
      default: false
    },
    phaseType: {
      type: String,
      default: '1'
    },
    isOldProject:{
      type: String,
      default: '0'
    },
    disabled:{
      type: Boolean,
      default: false
    },
    closeOp:{
      type: Boolean,
      default: false
    },
    useOldData: {
      type: Boolean,
      default: false
    },
    oldData: {
      type: Array,
      default: () => [],
    },
    fromType:String
  },
  data() {
    return {
      diffData: [],
      diffData2: [],
      companyLoading: false,
      companyOptions: [],
      nameLoading: false,
      nameOptions: [],
      dialog:{
        objId: null,
        header: '',
        open_detail: false,
        name: '',
        openSearchMember: false,
        type: ''
      },
      rowIndex: null,
      dayjs,
      dialogOpen: false,
      currentTab: "1",
      header: "添加",
      profTitOptions: [],
      deptMenuOptions: [],
      oldMember: null,
      visible: false,
      formData: {
        name: '',
        sex: '',
        birthDate: '',
        duty: '',
        profTit: '',
        profTitId: null,
        majorName: '',
        majorNowName: '',
        company: '',
        task: '',
        education: '',
        idCard: '',
        isAssist: '0',
        isInnerCompany:'1',
        contribution: '',
        degree: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: "姓名不能为空",
          }
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          }
        ],
        birthDate: [
          {
            required: true,
            message: "出生年月不能为空",
          }
        ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          }
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          }
        ],
        profTitId: [
          {
            required: true,
            message: "技术职称不能为空",
          }
        ],
        education: [{
          required: true,
          message: "学历不能为空",
        }],
        degree: [{
          required: true,
          message: "学位不能为空",
        }],
        majorName: [
          {
            required: true,
            message: "所学专业不能为空",
          }
        ],
        majorNowName: [
          {
            required: true,
            message: "现从事专业不能为空",
          }
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        task: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        isInnerCompany: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空",
          },
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
      },
      rules2: {
        name: [
          {
            required: true,
            message: "姓名不能为空",
          }
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          }
        ],
        // birthDate: [
        //   {
        //     required: true,
        //     message: "出生年月不能为空",
        //   }
        // ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          }
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          }
        ],
        profTitId: [
          {
            required: true,
            message: "技术职称不能为空",
          }
        ],
        education: [{
          required: true,
          message: "学历不能为空",
        }],
        majorName: [
          {
            required: true,
            message: "所学专业不能为空",
          }
        ],
        majorNowName: [
          {
            required: true,
            message: "现从事专业不能为空",
          }
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        task: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        isInnerCompany: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        // idCard: [
        //   {
        //     required: true,
        //     message: "身份证号不能为空",
        //   },
        //   {
        //     message: "身份证号不正确",
        //     pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
        //   },
        // ],
      },
      data7: [],
      data8: [],
      data: [],
      columns6: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          checkProps: ({row}) => ({disabled: row.type === '1'}),
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "name",
          title: "姓名",
          align: "center",
          width: 100
        },
        {
          colKey: "sex",
          title: "性别",
          align: "center",
          width: 60
        },
        {
          colKey: "idCard",
          title: "身份证号",
          align: "center",
          width: 180
        },
        {
          colKey: "birthDate",
          title: "出生年月",
          align: "center",
          width: 100
        },

        {
          colKey: "duty",
          title: "职务",
          align: "center",
          width: 150
        },
        {
          colKey: "profTitId",
          title: "技术职称",
          align: "center",
          width: 180
        },
        // {
        //   colKey: "profTit",
        //   title: "职称",
        //   align: "center",
        //   width: 100
        // },
        {
          colKey: "education",
          title: "学历",
          align: "center",
          width: 100
        },
        {
          colKey: "degree",
          title: "学位",
          align: "center",
          width: 100
        },
        {
          colKey: "majorName",
          title: "所学专业",
          align: "center",
        },
        {
          colKey: "majorNowName",
          title: "现从事专业",
          align: "center",
          width: 100
        },
        {
          colKey: "company",
          title: "所在单位",
          align: "center",
        },
        {
          colKey: "task",
          title: "在本项目中承担的任务",
          align: "center",
          width: 200
        },
        {
          colKey: "isAssist",
          title: "辅助人员",
          align: "center",
        },
      ],
      columns7: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "name",
          title: "姓名",
          align: "center",
          width: 100
        },
        {
          colKey: "sex",
          title: "性别",
          align: "center",
          width: 60
        },
        {
          colKey: "idCard",
          title: "身份证号",
          align: "center",
          width: 180
        },
        {
          colKey: "birthDate",
          title: "出生年月",
          align: "center",
          width: 100
        },

        {
          colKey: "duty",
          title: "职务",
          align: "center",
          width: 150
        },
        {
          colKey: "profTitId",
          title: "技术职称",
          align: "center",
          width: 180
        },
        // {
        //   colKey: "profTit",
        //   title: "职称",
        //   align: "center",
        //   width: 100
        // },
        {
          colKey: "education",
          title: "学历",
          align: "center",
          width: 100
        },
        {
          colKey: "degree",
          title: "学位",
          align: "center",
          width: 100
        },
        {
          colKey: "majorName",
          title: "所学专业",
          align: "center",
        },
        {
          colKey: "majorNowName",
          title: "现从事专业",
          align: "center",
          width: 100
        },
        {
          colKey: "company",
          title: "所在单位",
          align: "center",
        },
        {
          colKey: "task",
          title: "在本项目中承担的任务",
          align: "center",
          width: 200
        },
        {
          colKey: "isAssist",
          title: "辅助人员",
          align: "center",
        },
      ],
      columns8: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          checkProps: ({row}) => ({disabled: row.type === '1'}),
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "name",
          title: "姓名",
          align: "center",
          width: 100
        },
        {
          colKey: "sex",
          title: "性别",
          align: "center",
          width: 60
        },
        {
          colKey: "idCard",
          title: "身份证号",
          align: "center",
          width: 180
        },
        {
          colKey: "birthDate",
          title: "出生年月",
          align: "center",
          width: 100
        },

        {
          colKey: "duty",
          title: "职务",
          align: "center",
          width: 150
        },
        {
          colKey: "profTitId",
          title: "技术职称",
          align: "center",
          width: 180
        },
        // {
        //   colKey: "profTit",
        //   title: "职称",
        //   align: "center",
        //   width: 100
        // },
        {
          colKey: "education",
          title: "学历",
          align: "center",
          width: 100
        },
        {
          colKey: "degree",
          title: "学位",
          align: "center",
          width: 100
        },
        {
          colKey: "majorName",
          title: "所学专业",
          align: "center",
        },
        {
          colKey: "majorNowName",
          title: "现从事专业",
          align: "center",
          width: 100
        },
        {
          colKey: "company",
          title: "所在单位",
          align: "center",
        },
        {
          colKey: "task",
          title: "在本项目中承担的任务",
          align: "center",
          width: 200
        },
      ],
      columns9: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "name",
          title: "姓名",
          align: "center",
          width: 100
        },
        {
          colKey: "sex",
          title: "性别",
          align: "center",
        },
        {
          colKey: "idCard",
          title: "身份证号",
          align: "center",
          width: 180
        },
        {
          colKey: "birthDate",
          title: "出生年月",
          align: "center",
        },

        {
          colKey: "duty",
          title: "职务",
          align: "center",
          width: 150
        },
        {
          colKey: "profTitId",
          title: "技术职称",
          align: "center",
          width: 180
        },
        // {
        //   colKey: "profTit",
        //   title: "职称",
        //   align: "center",
        // },
        {
          colKey: "education",
          title: "学历",
          align: "center",
          width: 100
        },
        {
          colKey: "degree",
          title: "学位",
          align: "center",
          width: 100
        },
        {
          colKey: "majorName",
          title: "所学专业",
          align: "center",
        },
        {
          colKey: "majorNowName",
          title: "现从事专业",
          align: "center",
          width: 100
        },
        {
          colKey: "company",
          title: "所在单位",
          align: "center",
        },
        {
          colKey: "task",
          title: "在本项目中承担的任务",
          align: "center",
          width: 200
        },
      ],
      selectedMemberRowKeys: [],
      selectedMember1RowKeys: [],
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if(val && val.length>0 && this.useOldData){
          const newArr = val.map(data=>({
            ...data,
            initType: 'init'
          }))
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr;
            this.data7 = this.data.filter((val) => ['1', '2'].includes(val.type));
            this.data8 = this.data.filter((val) => ['3'].includes(val.type));
          }
        }
      }
    },
    projectId: {
      immediate: true,
      handler(val) {
        if (val) {
          if(this.phaseType === '4'){
            const addColumn = {
              colKey: "contribution",
              // title: "对成果创造性贡献",
              align: "center",
              fixed:"right",
              width: 200,
              title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>对成果创造性贡献</div>,
            }
            this.columns6.push(addColumn);
            this.columns8.push(addColumn);
            this.columns7.push(addColumn);
            this.columns9.push(addColumn);
          }
          this.getMember(val);
        }
      }
    },
    data7: {
      deep: true,
      immediate: true,
      handler(val) {
        const data = this.data7.concat(this.data8).map((val) => ({...val, phaseType: this.phaseType}))
        const newData = data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    data8: {
      deep: true,
      immediate: true,
      handler(val) {
        const data = this.data7.concat(this.data8).map((val) => ({...val, phaseType: this.phaseType}))
        const newData = data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    oldData: {
      deep: true,
      immediate: true,
      handler(val) {
        this.diffData = val.filter((val) => ['1', '2'].includes(val.type));
        this.diffData2 = val.filter((val) => ['3'].includes(val.type));
      }
    },
  },
  created() {
    this.getDeptTreeSelect(this.$store.state.user.deptId);
    this.getProfTitTreeSelect();
  },
  methods: {
    checkData() {
      const isValidate = this.data7.every((val, index) => {
        if (!val.contribution) {
          this.$set(this.data7[index], 'contributionStatus', 'error')
          this.$message.error(`项目负责人：第${index + 1}条对成果创造性贡献不能为空`);
          return false;
        }
        this.$set(this.data7[index], 'contributionStatus', 'default')
        return true;
      });
      if(!isValidate){
        return isValidate;
      }
      const isValidate2 = this.data8.every((val, index) => {
        if (!val.contribution) {
          this.$set(this.data8[index], 'contributionStatus', 'error')
          this.$message.error(`主要研究人员：第${index + 1}条对成果创造性贡献不能为空`);
          return false;
        }
        this.$set(this.data8[index], 'contributionStatus', 'default')
        return true;
      });

      return isValidate2
    },
    createCompanyOptions(value){
      this.companyOptions.push({
        label:`${value}`,
        value,
      });
    },
    remoteCompanyMethod(search){
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName:search}).then(response => {
        this.companyOptions = response.data.map(val=>  ({
          ...val,
          label:`${val.deptName}`,
          value:val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange(val,content){
      const index = this.nameOptions.findIndex(val=>content.option?.id === val.id)
      this.nameOptions[index].label= this.nameOptions[index].name;
      this.$set(this.nameOptions,index,this.nameOptions[index])
      Object.assign(this.formData, content.option  || this.nameOptions[index])
    },
    createNameOptions(value){
      this.nameOptions.push({
        label:`${value}`,
        value,
        name: value
      });
    },
    remoteNameMethod(search){
      this.nameLoading = true;
      this.$api.system.member.searchList({name:search}).then(response => {
        this.nameOptions = response.data.map(val=>  ({
          ...val,
          label:`${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.nameLoading = false;
      }).catch((e) => {
        this.nameLoading = false;
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange(val,content){
      this.formData.profTit = content.node.data.level;
    },
    onOldMember(){
      this.formData = {
        ...this.oldMember,
        projectId: this.projectId,
        phaseType: this.phaseType,
        type: this.currentTab === '1'?'2':'3',
        id: Number(new Date().getTime()) + Number(Math.random() * 10),
      };
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday.slice(0,7)
        this.$api.kjxm.project.findProjectMember(val).then(response => {
          this.oldMember = response.data;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    deptChange(value) {
      this.formData.company = value || this.formData.company;
    },
    getDeptTreeSelect(id) {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
        // this.menuOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect() {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    async getMember() {
      // 显示外层带的数据不查询
      if(this.useOldData){
        return false;
      }
      let responseLength = 0
      await this.$api.kjxm.project.memberGet(this.projectId, this.phaseType).then(response => {
        responseLength = response.data.length
        response.data = response.data.map((row, index) => ({...row, index}));
        this.data7 = response.data.filter((val) => ['1', '2'].includes(val.type));
        this.data8 = response.data.filter((val) => ['3'].includes(val.type));
                
      }).catch((e) => {
        this.$message.error(e.toString());
      });

      // 如果数组为空则查项目的
      if (responseLength <= 0 && this.phaseType !== '1'  && this.editOpen === true) {
        let nowPhaseType
        if(Number(this.phaseType) === 31){
          nowPhaseType = 3
        }else {
          nowPhaseType = Number(this.phaseType) - 1 > 0 ? Number(this.phaseType) - 1 : 1
        }
        await this.$api.kjxm.project.memberGet(this.projectId, nowPhaseType).then(response => {
          response.data = response.data.map((row, index) => ({...row, index}));
          this.data7 = response.data.filter((val) => ['1', '2'].includes(val.type));
          this.data8 = response.data.filter((val) => ['3'].includes(val.type));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }

      if (this.data7.length <= 0) {
        this.$api.kjxm.project.get(this.projectId).then(pm => {
          // 添加默认承担单位
          this.data7 = [{
            projectId: this.projectId,
            type: '1',
            phaseType: this.phaseType,
            name: pm.data.projectLeader.name,
            sex: pm.data.projectLeader.sex,
            birthDate: pm.data.projectLeader.birthDate,
            profTit: pm.data.projectLeader.profTit,
            profTitId: pm.data.projectLeader.profTitId,
            majorName: pm.data.projectLeader.majorName,
            majorNowName: pm.data.projectLeader.majorNowName,
            company: pm.data.projectLeader.company,
            duty: pm.data.projectLeader.duty,
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            task: pm.data.projectLeader.task,
            idCard: pm.data.projectLeader.idCard,
            education: pm.data.projectLeader.education,
            degree: pm.data.projectLeader.degree,
            isAssist: '0',
            isInnerCompany: '1',
            contribution: '',
          }];
          const data = this.data7.concat(this.data8).map((val) => ({...val, phaseType: this.phaseType}))
          const newData = data.map((val, index) => ({...val, sort: index + 1}))
          this.$emit("input", newData);
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else {
        const data = this.data7.concat(this.data8).map((val) => ({...val, phaseType: this.phaseType}))
        const newData = data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }

    },
    upMember() {
      if (this.selectedMemberRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const data = this.data7.filter((val) => ['1'].includes(val.type));
      if(data.length>0){
        if (this.data7[1].id === this.selectedMemberRowKeys[0]) {
          this.$message.warning("已是第一行");
        } else {
          const index = this.data7.findIndex((val) => val.id === this.selectedMemberRowKeys[0])
          this.moveInArray(this.data7, index, index - 1)
        }
      }else{
        if (this.data7[0].id === this.selectedMemberRowKeys[0]) { // eslint-disable-line
          this.$message.warning("已是第一行");
        } else {
          const index = this.data7.findIndex((val) => val.id === this.selectedMemberRowKeys[0])
          this.moveInArray(this.data7, index, index - 1)
        }
      }

    },
    downMember() {
      if (this.selectedMemberRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data7[this.data7.length - 1].id === this.selectedMemberRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data7.findIndex((val) => val.id === this.selectedMemberRowKeys[0])
        this.moveInArray(this.data7, index, index + 1)
      }
    },
    updateMember() {
      if (this.selectedMemberRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return false;
      }
      const index = this.data7.findIndex((val) => val.id === this.selectedMemberRowKeys[0])
      Object.assign(this.formData, this.data7[index])
      this.rowIndex = index;
      this.currentTab = '1';
      this.header = "修改项目其他负责人"
      this.dialogOpen = true;
      this.visible = true;

    },
    delMember() {
      if (this.selectedMemberRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data7.findIndex((val) => val.id === this.selectedMemberRowKeys[0])
      this.data7.splice(index, 1)
      this.selectedMemberRowKeys = [];
    },
    upMember2() {
      if (this.selectedMember1RowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data8[0].id === this.selectedMember1RowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data8.findIndex((val) => val.id === this.selectedMember1RowKeys[0])
        this.moveInArray(this.data8, index, index - 1)
      }
    },
    updateMember2() {
      if (this.selectedMember1RowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return false;
      }
      const index = this.data8.findIndex((val) => val.id === this.selectedMember1RowKeys[0])
      Object.assign(this.formData,this.data8[index])
      // this.formData = this.data8[index]
      this.rowIndex = index;
      this.currentTab = '2';
      this.header = "修改项目主要研究人员"
      this.dialogOpen = true;
      this.visible = true;
    },
    downMember2() {
      if (this.selectedMember1RowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data8[this.data8.length - 1].id === this.selectedMember1RowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data8.findIndex((val) => val.id === this.selectedMember1RowKeys[0])
        this.moveInArray(this.data8, index, index + 1)
      }
    },
    delMember2() {
      if (this.selectedMember1RowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data8.findIndex((val) => val.id === this.selectedMember1RowKeys[0])
      this.data8.splice(index, 1);
      this.selectedMember1RowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit(type) {
      if (this.currentTab === '1' && this.data7.length >= 3 && this.rowIndex === null) {
        this.$message.error("项目负责人最多3人");
        return;
      }

      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {

          // const age = getIdCardAge(this.formData.idCard)
          // if (age < 18) {
          //   this.$message.error(`身份证号 需满18岁`);
          //   return false
          // }
          const birthday = getIdCardBirthday(this.formData.idCard)
          // if (birthday.includes(this.formData.birthDate)) {
          //   this.$message.error(`身份证号 与 出生年月 不一致`);
          //   return false
          // }
          if (this.currentTab === '1') {
            if (this.rowIndex !== null) {
              this.$set(this.data7, this.rowIndex, {
                projectId: this.projectId,
                phaseType: this.phaseType,
                ...this.formData,
              })
              this.$message.success("修改成功");
              this.$refs.form.reset();
              this.dialogOpen = false;
              this.visible = false;
              this.rowIndex = null;
            } else {
              const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
              this.data7.push({
                ...this.formData,
                id:newId,
                projectId: this.projectId,
                type: '2',
                phaseType: this.phaseType,
              })
            }
          } else{
            if (this.rowIndex !== null) {  // eslint-disable-line
              this.$set(this.data8, this.rowIndex, {
                projectId: this.projectId,
                phaseType: this.phaseType,
                ...this.formData,
              })
              this.$message.success("修改成功");
              this.$refs.form.reset();
              this.dialogOpen = false;
              this.visible = false;
              this.rowIndex = null;
            } else {
              const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
              this.data8.push({
                ...this.formData,
                id:newId,
                projectId: this.projectId,
                type: '3',
                phaseType: this.phaseType,
              })
            }
          }
          this.$refs.form.reset();
          if(type===1){
            this.onClose()
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onClose() {
      this.oldMember = null;
      this.$refs.form.reset();
      this.formData.isAssist = "0"
      this.visible = false;
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
